/**
 * Created by 小敏哥 on 2018/1/2.
 */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import IllegalDetailItem from '../../components/illegalDetailList/illegalDetailItem';
import {getIllegalList, getFinishedRequirements,illegalList} from '../../actions/illegalDetailListAction'
import {backendids} from '../../actions/addMessageAction';
import {prepareUserOrder} from '../../actions/payMentAction'
import style from './index.scss';
import common from '../../../../../../../src/js/utils/common';
import Remodal from '../../../../../../../src/js/components/reModal';
import {Toast} from 'antd-mobile';

class IllegalDetailList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            checkAll: true,
            allCount: 0,//选中项数
            allFine: 0,//选中罚款
            allDegree: 0,//选中扣分
            allCountMessage: {
                count: 0,
                fine: 0,
                degree: 0,
            }//所有汇总后的违章信息
        };

        this.checkData = {};//所有违章的选中状态记录，记录backendId
        this.violationData = {};//记录所有违章的violationId
        this.dataListForOrder=[];//存放所有backendId和记录所有违章的violationId，由于后端数据有排序需求，而原有数据结构为对象，属于无序状态，此处存放数据用于做对照
        this.checkedItemWithRules = 0;//选中的需要补充资料的条数
        this.allItemWithRules = 0;//所有需要补充资料的违章条数;
        this.allIllegalCount = 0;//所有可办违章的条数统计
    }

    componentDidMount() {
        common.setViewTitle(decodeURIComponent(this.props.params.carNumber));
        this.props.dispatch(getFinishedRequirements({carId: this.props.params.carId}, () => {
            this.props.dispatch(getIllegalList({
                carId: this.props.params.carId
            }, () => {
                //获取汇总信息
                this.getAllMessage();
            }))
        }));
    }


    //构建所需资料列表
    structProxyRule(orign) {
        let dataDic = {
            "CarOwnerLen": "车主姓名",
            "CarCodeLen": "车身架号",
            "CarDriveLen": "发动机号",
            "DrivingLicense": "行驶证主页图片",
            "DrivingSecondLicense": "行驶证副页图片",
            "MajorViolation": "驾驶证主页图片",
            "MajorSecondViolation": "驾驶证副页图片",
            "OwnerCardLen": "车主身份证号",
            "JashiZhengHaoLen": "驾驶证号",
            "XingShiZhengHaoLen": "行驶证档案编号",
            "CheliangZhengShuLen": "车辆登记证书号",
            "DanganBianHaoLen": "驾驶证档案编号",
            "CarOwnerPhoneLen": "车主联系电话",
            "TiaoXingMaLen": "驾驶证条形码",
            "VerifyCodeLen": "验证码",
            "FilePhoneLen": "驾驶证登记电话",
        };
        let resultArray = [];
        let orignObj = JSON.parse(orign);
        for (var item in orignObj) {
            if (orignObj[item] != '0') {
                let itemNumber = parseInt(orignObj[item]);
                //限制长度且已有资料长度小于限制长度
                if (itemNumber < 99 && this.props.finishedRequirements[item].length < itemNumber) {
                    resultArray.push(dataDic[item]);
                }
                //不限长度切已有资料为空
                else if (itemNumber == 99 && !this.props.finishedRequirements[item]) {
                    resultArray.push(dataDic[item]);
                }
            }
        }
        return resultArray;
    }

    //根据全选状态和需要补全的资料确定选中状态
    getItemCheckedStatus(rule, backendId, violationId) {
        //全选走这个分支
        if (this.state.checkAll) {
            this.checkData[backendId] = true;
            this.violationData[violationId] = true;
            this.checkedItemWithRules = this.allItemWithRules;//加满
            return true;
        }
        //初始化分支，默认不全选会走这个分支
        else if (this.checkData[backendId] !== false) {
            this.checkData[backendId] = true;
            this.violationData[violationId] = true;
            return true;
        }
        //已选中分支
        else if (this.checkData[backendId]) {
            return true;
        }
        else {
            return false;
        }
    }


    //设置选中违章计算后的信息
    setCheckedCountMessage() {
        let allCount = 0,//选中项数
            allFine = 0,//选中罚款
            allDegree = 0//选中扣分
        for (var index in this.props.illegalList) {
            if (this.checkData[this.props.illegalList[index].backendId]) {
                allCount++;
                allFine = allFine + this.props.illegalList[index].fine;
                allDegree = this.props.illegalList[index].other == '0' ? allDegree : (allDegree + parseInt(this.props.illegalList[index].degree));
            }
        }
        if (allCount != this.state.allCount || allFine != this.state.allFine || allDegree != this.state.allDegree) {
            this.setState({
                allCount: allCount,//选中项数
                allFine: allFine,//选中罚款
                allDegree: allDegree//选中扣分
            })
        }
    }

    //获取所有违章汇总信息
    getAllMessage() {
        let allCount = 0,//选中项数
            allFine = 0,//选中罚款
            allDegree = 0//选中扣分
        for (var index in this.props.illegalList) {
            let item = this.props.illegalList[index];
            if (item.canProcess == '1') {
                this.dataListForOrder.push({backendId:item.backendId,violationId:item.violationId});
                let rules = this.structProxyRule(item.proxyRule);
                rules.length > 0 && this.allItemWithRules++;//统计所有需要添加资料的违章的条数
                this.allIllegalCount++;
            }
            allCount++;
            allFine = allFine + item.fine;
            allDegree = allDegree + parseInt(item.degree);//other为0时可不扣分执行
        }
        this.setState({
            allCountMessage: {
                count: allCount,//所有违章项数
                fine: allFine,//选中罚款
                degree: allDegree//选中扣分
            }
        })
    }


    //检测当前是否所有选项都选中
    setIsAllCheck() {
        let checkCount = 0;
        let isCheckAll = false;
        for (var index in this.checkData) {
            if (this.checkData[index]) {
                checkCount++;
            }
        }
        if (checkCount == this.allIllegalCount) {
            isCheckAll = true;
        }
        //更改全选状态
        this.setState({
            checkAll: isCheckAll,
        });
    }

    //单个选中状态改变
    itemCheckStatusChange(violationId, backendId, checked, rules) {
        if (rules.length > 0) {
            if (checked) {
                this.checkedItemWithRules++;
            }
            else {
                //取消全选
                /*this.setState({
                    checkAll:false,
                });*/
                this.checkedItemWithRules--;
            }
        }
        this.checkData[backendId] = checked;
        this.violationData[violationId] = checked;
        this.setIsAllCheck();
        this.setCheckedCountMessage();
        console.log(this.checkData);
        console.log(this.checkedItemWithRules);
    }

    componentDidUpdate() {
        this.setCheckedCountMessage();
    }

    componentWillUnmount(){
        //退出页面时清除数据，防止数据互串
        this.props.dispatch(illegalList(null));
    }

    structList() {
        return this.props.illegalList && this.props.illegalList.length > 0 ? this.props.illegalList.map((item, index) => {
            let rules = this.structProxyRule(item.proxyRule);
            //不等于1即不可代办，此时直接传未选中
            let checkStatus = item.canProcess == '1' && this.getItemCheckedStatus(rules, item.backendId, item.violationId);
            //this.checkData[item.backendId] = checkStatus;
            this.setCheckedCountMessage();
            return <div className={style.illegalItem} key={item.backendId}>
                <IllegalDetailItem enable={item.canProcess == '1'} backendId={item.backendId} forceStatus={checkStatus}
                                   title={item.locationName + item.location}
                                   archive={item.archive ? item.archive : '无'}
                                   canProcessMsg={item.canProcessMsg} degree={item.degree} fine={item.fine}
                                   occurTime={common.transfromDateTime(new Date(item.occurTime))} reason={item.reason}
                                   proxyRule={rules} statusChange={(backendId, checked) => {
                    this.itemCheckStatusChange(item.violationId, backendId, checked, rules);
                }}></IllegalDetailItem>
            </div>
        }) : <img className={style.empty} src="./images/IllegalDetails.png"/>;
    }


    //全选
    setCheckAllStatus() {
        this.allIllegalCount > 0 && this.setState({
            checkAll: !this.state.checkAll
        }, () => {
            this.checkedItemWithRules = 0;
            if (this.state.checkAll) {
                for (let item of this.props.illegalList) {
                    //记录需要上传资料的项的条数

                    let rules = this.structProxyRule(item.proxyRule);
                    if (rules.length > 0 && item.canProcess == '1') {
                        this.checkedItemWithRules++;
                    }
                    this.checkData[item.backendId] = (item.canProcess == '1');//不可代办的全选亦不选中
                    this.violationData[item.violationId] = (item.canProcess == '1');//不可代办的全选亦不选中
                }
            }
            else {
                for (let item of this.props.illegalList) {
                    this.checkData[item.backendId] = false;
                    this.violationData[item.violationId] = false;
                }
            }
            //设置计算后的属性
            this.setCheckedCountMessage();
        })
    }

    goToCarDetail() {
        this.context.router.push(`carDetail/${this.props.params.carId}`);
    }

    //跳转到确认订单页面
    submit() {
        let backendIds = [];
        let violationIds = [];
        let backendStr = "";
        let violationIdStr = "";
        for(let item of this.dataListForOrder){
            if (this.checkData[item.backendId]) {
                backendIds.push(item.backendId);
            }
            if(this.violationData[item.violationId]){
                violationIds.push(item.violationId);
            }
        }
        /*for (let index in this.checkData) {
            if (this.checkData[index]) {
                backendIds.push(index);
            }
        }
        for (let index in this.violationData) {
            if (this.violationData[index]) {
                violationIds.push(index);
            }
        }*/
        if (backendIds.length == 0) {
            Toast.info('请选择违章', 2);
            return;
        }
        //缓存数据共订单确认页调用
        sessionStorage.setItem('illegal_backendIds', backendStr = backendIds.join(','));
        sessionStorage.setItem('illegal_violationIds', violationIdStr = violationIds.join(','));
        sessionStorage.setItem('illegal_carId', this.props.params.carId);
        //检测到需要补充资料
        if (this.checkedItemWithRules > 0) {
            Remodal.confirm('您需要补充材料才能办理', () => {
                this.props.dispatch(backendids(backendIds));
                this.context.router.push(`addMessage/${this.props.params.carId}`);
            })
        }
        else {
            this.props.dispatch(prepareUserOrder({
                carId: this.props.params.carId,
                violationIds: violationIdStr,
                backendIds: backendStr,
                couponId: '',
                isUrgent: true,
                phone: ""
            }, (result) => {
                this.context.router.push(`payment`);
            }))
        }

    }

    getAllCheckImg() {
        if (this.state.checkAll) {
            return this.allIllegalCount > 0 ? './images/checked.png' : './images/icon-check_disable.png';
        }
        else {
            return this.allIllegalCount > 0 ? './images/no_checked.png' : './images/icon-check_disable.png';
        }
    }

    render() {
        return <div className={style.illegalDetailList}>
            <div className={style.redTips}>
                <div>
                    <span>{`违章${this.state.allCountMessage.count}条`}</span><span>{`罚款${this.state.allCountMessage.fine}元`}</span><span>{`扣分${this.state.allCountMessage.degree}分`}</span>
                </div>
                <div onClick={this.goToCarDetail.bind(this)}><span>车辆详情</span><img src="./images/arrowright_while.png"/>
                </div>
            </div>
            {this.structList()}
            <div className={style.space}></div>
            {this.props.illegalList && this.props.illegalList.length > 0 ? <div className={style.bottomMenu}>
                <img src={this.getAllCheckImg()} onClick={() => {
                    this.setCheckAllStatus()
                }}/>
                <div className={style.all}>全选</div>
                <div className={style.detail}>
                    <div>{`已选${this.state.allCount}笔`}</div>
                    <div>{`共计罚款￥${this.state.allFine}，扣${this.state.allDegree}分`}</div>
                </div>
                <button onClick={() => {
                    this.submit()
                }}>去办理
                </button>
            </div> : ''}
        </div>
    }
}


//使用context
IllegalDetailList.contextTypes = {
    router: React.PropTypes.object.isRequired
};


function mapStateToProps(state) {
    return Object.assign({}, state.illegalDetailInfo);
}

export default connect(mapStateToProps)(IllegalDetailList);